//
//  MGViewController.m
//  MGPolymerAdSDK
//
//  Created by 790879770@qq.com on 11/15/2023.
//  Copyright (c) 2023 790879770@qq.com. All rights reserved.
//


#import "FiddleViewController.h"
#import "Masonry.h"
#import "NSDate+MGRecently.h"
#import "FiddleListTableViewCell.h"

#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>

#import <SDWebImageWebPCoder/SDImageWebPCoder.h>

#import "UIPlayer.h"

@interface FiddleListModel : NSObject
@property (nonatomic, copy  ) NSString *filePath;
@property (nonatomic, copy  ) NSString *fileName;
@property (nonatomic, copy  , readonly) NSString *fullPath;

@end
@implementation FiddleListModel
- (NSString *)fullPath {
    return [_filePath stringByAppendingPathComponent:_fileName];
}
@end


/// 文件类型
@interface FiddleFileType : NSObject

@end
@implementation FiddleFileType
@end

/// 文件信息
@interface FiddleFileInfo : NSObject
{
    @private
    NSString *_fullPath;
}
- (instancetype)initWithFullPath:(NSString *)fullPath;
- (NSString *)createTime;
- (NSInteger)referenceCount;
- (NSInteger)fileSize;
@end
@implementation FiddleFileInfo
- (instancetype)initWithFullPath:(NSString *)fullPath {
    if (self = [super init]) {
        _fullPath = fullPath;
    }
    return self;
}

- (NSString *)createTime {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:_fullPath error:nil];
    NSDate *creationDate = [fileAttributes objectForKey:NSFileCreationDate];
    if ([creationDate isToday]) {
        return [NSString stringWithFormat:@"今天 %@", [creationDate formatDate:@"HH:mm"]];
    } else if ([creationDate isYesterday]) {
        return [NSString stringWithFormat:@"昨天 %@", [creationDate formatDate:@"HH:mm"]];
    } else {
        return [creationDate formatDate:@"YYYY/MM/dd HH:mm"];
    }
}

- (NSInteger)referenceCount {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager contentsOfDirectoryAtPath:_fullPath error:NULL].count;
}
// 字节
- (NSInteger)fileSize {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:_fullPath]) {
        return [fileManager attributesOfItemAtPath:_fullPath error:nil].fileSize;
    }
    return 0;
}
@end


/// 文件缩略图
@interface FiddleFileThumb : NSObject

@end
@implementation FiddleFileThumb
@end





#pragma mark - FiddleViewController
@interface FiddleViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UILabel *crumbsLabel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSString *currentPath;
@property (nonatomic, strong) NSArray *data;

@end

@implementation FiddleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self.view addSubview:self.crumbsLabel];
    [self.view addSubview:self.tableView];
    [self.crumbsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(0.5);
        make.left.right.equalTo(self.view).inset(12);
        make.height.mas_equalTo(28);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.crumbsLabel.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    //self.tableView.frame = self.view.bounds;
    
    
    self.title = self.currentPath.length ? [self.currentPath componentsSeparatedByString:@"/"].lastObject : @"我的Home";
    self.crumbsLabel.text = self.currentPath.length ? [self.currentPath substringFromIndex:NSHomeDirectory().length] : @"/";
    
    [self fetchData];
}

- (void)fetchData {
    if (!self.currentPath.length) {
        [self acquireRootDir];
    }
    [self listOfDir:self.currentPath];
}

- (BOOL)isDirectory:(NSString *)filePath {
    BOOL isDir = NO;
    [NSFileManager.defaultManager fileExistsAtPath:filePath isDirectory:&isDir];
    return isDir;
}
- (BOOL)isImageFile:(NSString *)filePath {
    BOOL is = NO;
    is = 
    [filePath hasSuffix:@".jpg"] ||
    [filePath hasSuffix:@".jpeg"] ||
    [filePath hasSuffix:@".png"] ||
    [filePath hasSuffix:@".gif"];
    return is;
}

- (BOOL)isWebPFile:(NSString *)filePath {
    BOOL is = NO;
    is = [filePath hasSuffix:@".webp"];
    return is;
}

- (BOOL)isVideoFile:(NSString *)filePath {
    BOOL is = NO;
    is =
    [filePath hasSuffix:@".mp4"] ||
    [filePath hasSuffix:@".mov"] ||
    [filePath hasSuffix:@".avi"] ||
    [filePath hasSuffix:@".mkv"];
    return is;
}
- (BOOL)isJSONFile:(NSString *)filePath {
    BOOL is = NO;
    is = [filePath hasSuffix:@".json"];
    return is;
}
- (BOOL)isXMLFile:(NSString *)filePath {
    BOOL is = NO;
    is = [filePath hasSuffix:@".xml"];
    return is;
}
- (BOOL)isPlistFile:(NSString *)filePath {
    BOOL is = NO;
    is = [filePath hasSuffix:@".plist"];
    return is;
}
- (BOOL)isTextFile:(NSString *)filePath {
    BOOL is = NO;
    is = [filePath hasSuffix:@".txt"] ||
    [filePath hasSuffix:@".log"];
    return is;
}
- (BOOL)isOtherTextFile:(NSString *)filePath {
    BOOL is = NO;
    is = [filePath hasSuffix:@".html"] ||
    [filePath hasSuffix:@".css"] ||
    [filePath hasSuffix:@".js"];
    return is;
}

- (NSArray *)listOfDir:(NSString *)filePath {
    NSArray *files = [NSFileManager.defaultManager contentsOfDirectoryAtPath:filePath error:NULL];
    NSLog(@"");
    self.data = files;
    [self.tableView reloadData];
    return files;
}
- (void)acquireRootDir {
    NSString *home = NSHomeDirectory();
    if ([self isDirectory:home]) {
        // NSArray *files = [NSFileManager.defaultManager subpathsAtPath:home];
        // NSArray *contents = [NSFileManager.defaultManager contentsOfDirectoryAtPath:home error:NULL];
        // NSLog(@"");
        self.currentPath = home;
        //[self listOfDir:home];
    }
    NSLog(@"---home: %@", home);
}

#pragma mark - 侧滑删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *fullPath = [self.currentPath stringByAppendingPathComponent:self.data[indexPath.row]];
        [NSFileManager.defaultManager removeItemAtPath:fullPath error:NULL];
        [self fetchData];
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FiddleListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FiddleListTableViewCell" forIndexPath:indexPath];
    
    NSString *fullPath = [self.currentPath stringByAppendingPathComponent:self.data[indexPath.row]];
    if ([self isDirectory:fullPath]) {
        //cell.icon.image = [UIImage imageNamed:@"icon_wenjianjia"];
        cell.icon.image = [self imageInBundle:@"icon_wenjianjia"];
    } else if ([self isImageFile:fullPath]) {
        cell.icon.image = [UIImage imageWithContentsOfFile:fullPath];
    } else if ([self isWebPFile:fullPath]) {
        //cell.icon.image = [UIImage imageWithContentsOfFile:fullPath];
        cell.icon.image = [self previewWebP:fullPath];
    } else if ([self isVideoFile:fullPath]) {
        cell.icon.image = [self getVideoPreViewImage:fullPath];
    } else if ([self isJSONFile:fullPath]) {
        //cell.icon.image = [UIImage imageNamed:@"icon_json"];
        cell.icon.image = [self imageInBundle:@"icon_json"];
    } else if ([self isXMLFile:fullPath] || [self isPlistFile:fullPath]) {
        //cell.icon.image = [UIImage imageNamed:@"icon_xml"];
        cell.icon.image = [self imageInBundle:@"icon_xml"];
    } else if ([self isTextFile:fullPath]) {
        //cell.icon.image = [UIImage imageNamed:@"icon_wenjian"];
        cell.icon.image = [self imageInBundle:@"icon_wenjian"];
    } else {
        //cell.icon.image = [UIImage imageNamed:@"icon_unknownfile"];
        cell.icon.image = [self imageInBundle:@"icon_unknownfile"];
    }
    
    cell.titleLabel.numberOfLines = 0;
    cell.titleLabel.text = self.data[indexPath.row];
    
    FiddleFileInfo *fileInfo = [[FiddleFileInfo alloc] initWithFullPath:fullPath];
    if ([self isDirectory:fullPath]) {
        // 文件夹
        cell.briefLabel.text = [NSString stringWithFormat:@"%@ - %ld项", fileInfo.createTime, fileInfo.referenceCount];
    } else {
        // 文件
        CGFloat kb = fileInfo.fileSize / 1000.0;
        CGFloat mb = kb / 1000.0;
        CGFloat gb = mb / 1000.0;
        NSString *size = nil;
        if (gb > 1) {
            size = [NSString stringWithFormat:@"%.1fGB", gb];
        } else if (mb > 1) {
            size = [NSString stringWithFormat:@"%.1fMB", mb];
        } else if (kb > 1) {
            size = [NSString stringWithFormat:@"%.1fKB", kb];
        } else {
            size = [NSString stringWithFormat:@"%ld字节", fileInfo.fileSize];
        }
        cell.briefLabel.text = [NSString stringWithFormat:@"%@ - %@", fileInfo.createTime, size];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    FiddleViewController *ctrl = [FiddleViewController new];
    NSString *fullPath = [self.currentPath stringByAppendingPathComponent:self.data[indexPath.row]];
    if ([self isDirectory:fullPath]) {
        [ctrl setValue:fullPath forKeyPath:@"currentPath"];
        [self.navigationController pushViewController:ctrl animated:YES];
    }
    else if ([self isImageFile:fullPath]) {
        UIImageView *imageView = [UIImageView new];
        imageView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.9];
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
        imageView.image = image;
        imageView.frame = self.view.bounds;
        [self.view addSubview:imageView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [imageView addGestureRecognizer:tap];
    }
    else if ([self isWebPFile:fullPath]) {
        UIImageView *imageView = [UIImageView new];
        imageView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.9];
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image = [self previewWebP:fullPath];
        imageView.frame = self.view.bounds;
        [self.view addSubview:imageView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [imageView addGestureRecognizer:tap];
    }
    else if ([self isVideoFile:fullPath]) {
        UIPlayer *player = [UIPlayer new];
        player.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.9];
        player.mediaURL = fullPath;
        player.frame = self.view.bounds;
        [self.view addSubview:player];
        [player play];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [player addGestureRecognizer:tap];
    }
    else if ([self isTextFile:fullPath] || [self isJSONFile:fullPath] || [self isPlistFile:fullPath] || [self isXMLFile:fullPath] || [self isOtherTextFile:fullPath]) {
        UITextView *textView = [UITextView new];
        NSString *text = [[NSString alloc] initWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:NULL];
        textView.text = text;
        //textView.frame = self.view.bounds;
        [self.view addSubview:textView];
        [textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.left.right.bottom.equalTo(self.view);
        }];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [textView addGestureRecognizer:tap];
    }
    
}

- (void)tap:(UITapGestureRecognizer *)tap {
    [tap.view removeFromSuperview];
}

- (UILabel *)crumbsLabel {
    if (!_crumbsLabel) {
        _crumbsLabel = [UILabel new];
        _crumbsLabel.font = [UIFont systemFontOfSize:10 weight:UIFontWeightLight];
        _crumbsLabel.textColor = UIColor.linkColor;
    }
    return _crumbsLabel;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.sectionHeaderHeight = 0;
        [_tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"UITableViewCell"];
        [_tableView registerClass:FiddleListTableViewCell.class forCellReuseIdentifier:@"FiddleListTableViewCell"];
    }
    return _tableView;
}

/// 获取webp图片
- (UIImage *)previewWebP:(NSString *)filePath {
    NSData *webPData = [NSData dataWithContentsOfFile:filePath];
    // 使用 SDWebImageWebPCoder 解码 WebP 图片
    SDImageWebPCoder *webPCoder = [SDImageWebPCoder sharedCoder];
    UIImage *image = [webPCoder decodedImageWithData:webPData options:nil];
    return image;
}

/// 获取webp图片的首帧
- (UIImage *)generateThumbnailFromWebP:(NSString *)filePath {
    // 读取 WebP 数据
    NSData *webPData = [NSData dataWithContentsOfFile:filePath];
    if (!webPData) {
        NSLog(@"无法读取 WebP 文件: %@", filePath);
        return nil;
    }

    // 创建 WebP 编解码器
    SDImageWebPCoder *webPCoder = [SDImageWebPCoder sharedCoder];

    // 解码选项：指定缩略图的最大尺寸
    SDImageCoderOptions *options = @{
        SDImageCoderDecodeFirstFrameOnly : @(YES)
    };
    
    // 解码为缩略图
    UIImage *thumbnail = [webPCoder decodedImageWithData:webPData options:options];
    if (!thumbnail) {
        NSLog(@"解码 WebP 缩略图失败");
        return nil;
    }

    return thumbnail;
}

// 获取视频第一帧
- (UIImage*)getVideoPreViewImage:(NSString *)path {
    //本地视频
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:path] options:nil];
    //网络视频
    AVURLAsset *asset2 = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:path] options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    if (videoImage == nil) {
        videoImage = [UIImage imageNamed:@"default_video.png"];
    }
    return videoImage;
}

- (NSString *)timeOfVideo:(NSString *)filePath {
    NSTimeInterval inteval = [self videoDuration:filePath];
    int h = inteval/60;
    int m = h/60;
    int s = m/60;
    return [NSString stringWithFormat:@"%@", @""];
}
- (NSTimeInterval)videoDuration:(NSString *)filePath {
    // 假设你已经有了视频文件的URL
    NSURL *videoURL = [NSURL fileURLWithPath:filePath];
     
    // 创建AVAsset对象
    AVAsset *asset = [AVAsset assetWithURL:videoURL];
     
    // 获取视频总时长
    NSTimeInterval duration = CMTimeGetSeconds(asset.duration);
     
    // 输出视频总时长
    NSLog(@"视频总时长：%f秒", duration);
    return duration;
}


- (UIImage *)imageInBundle:(NSString *)imageName {
    NSBundle *bundle = [NSBundle bundleForClass:self.classForCoder];
    NSURL *bundleURL = [[bundle resourceURL] URLByAppendingPathComponent:@"MGFileBrowser.bundle"];
    NSBundle *resourceBundle = [NSBundle bundleWithURL:bundleURL];
    UIImage *image = [UIImage imageNamed:imageName inBundle:resourceBundle compatibleWithTraitCollection:nil];
    return image;
}
@end


